<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <el-button @click="addCategory">添加分组</el-button>
      </el-col>
      <el-col :span="12">
        <el-input v-model="keywords" placeholder="搜索关键字" style="width: 200px; margin-right: 10px" clearable></el-input>
        <el-button type="primary" icon="Search" @click="query">搜索</el-button>
        <el-button type="primary" icon="Upload" @click="showUploadDia">上传</el-button>
      </el-col>
    </el-row>
    <div class="images_tags_wrapper">
      <div class="tags">
        <el-tabs :tab-position="tabPosition" v-model="activeTabName" @tab-click="handleTabClick">
          <el-tab-pane label="全部" name="all" :key="all"></el-tab-pane>
          <el-tab-pane v-for="item in categoryList" :label="item.name" :name="item.code" :key="item.code"> </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 图片显示区域 -->
      <div class="img_lists">
        <div class="group_name">
          <div class="name">
            {{ currentCategoryInfo.name }}
          </div>
          <div class="d-flex align-center ml-1" v-if="currentCategoryInfo.code !== 'all'">
            <el-button type="primary" text="" :icon="Edit" @click="reName">重命名</el-button>
            <el-button type="danger" text="" :icon="Delete" @click="delOneCategory">删除</el-button>
          </div>
        </div>
        <div class="image-table">
          <template v-if="images.length">
            <div v-for="item in images" :key="item.id" class="image-table-col">
              <div class="image-table-col-border">
                <div class="image-table-image dis-fl dis-jc-c dis-ai-c">
                  <el-image :max-scale="7" :min-scale="0.2" :src="item.url" :preview-src-list="[item.url]" fit="cover" lazy />
                </div>
                <div class="image-table-footer">
                  <div class="imgae-name dis-fl dis-jc-c dis-ai-c">
                    <el-checkbox v-if="openInDialog" v-model="checked" :true-label="item.url" @change="handleSelect"></el-checkbox>
                    <span>{{ item.filename }}</span>
                  </div>
                  <div class="image-table-footer-btn">
                    <el-button type="primary" text="" size="small" @click="editHanle(item)">改名</el-button>
                    <el-button type="primary" text="" size="small" @click="pictureLink(item)">链接</el-button>
                    <el-dropdown trigger="click" @command="changeClasstify($event, item)">
                      <span class="el-dropdown-link"> 分组<i class="el-icon-arrow-down el-icon--right" /> </span>
                      <el-dropdown-menu slot="dropdown" class="class-drop">
                        <el-dropdown-item command="-1">全部分组</el-dropdown-item>
                        <el-dropdown-item v-for="(item, index2) in categoryList" :key="index2" :command="item.id">{{ item.name }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <el-button class="deltet-btn" type="primary" text="" size="small" @click="deleteImg(item._id)">删除</el-button>
                  </div>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <el-empty style="width: 100%" :image-size="200" />
          </template>
        </div>
        <Pagination :total="pages.total" v-model:pageNum="pages.pageNum" v-model:pageSize="pages.pageSize" @change="query"></Pagination>
      </div>
    </div>
    <!-- 上传弹窗 -->
    <el-dialog v-model="state.visiableUpload" title="上传图片" center :destroy-on-close="true" :close-on-click-modal="false" width="35%">
      <Uploader ref="uploaderRef"></Uploader>
      <template #footer>
        <el-button @click="state.visiableUpload = false">取消</el-button>
        <el-button type="primary" :loading="state.confirmBtnLoading" @click="handleUpload">确认</el-button>
      </template>
    </el-dialog>
    <!-- 添加/修改分组弹窗 -->
    <Dialog ref="dialogRef" :title="dialogOptions.title" :width="dialogOptions.width" @confirm="confirmOnDialog">
      <template v-slot:content>
        <el-form :model="dialogData" ref="diaformRef" label-width="100px" label-position="left">
          <el-form-item label="分组名称" prop="name">
            <el-input v-model="dialogData.name" placeholder="分组名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="分组Code" prop="code">
            <el-input v-model="dialogData.code" placeholder="分组Code(不可重复)" clearable></el-input>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>

    <!-- 修改图片名称 -->
    <Dialog ref="updateImgRef" title="修改图片名称" width="300px" @confirm="confirmUpdateImg">
      <template v-slot:content>
        <el-input v-model="imgName" placeholder="请输入图片名称" clearable></el-input>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from "vue";
import { Delete, Edit } from "@element-plus/icons-vue";
import { copyText } from "vue3-clipboard";
import { updateImage, getImageList, updateCategory, getCategories, createCategory, delCategory, delImg, delFileHard } from "@/api/usualManage";
import { FSSaveAs, resetForm } from "@/utils/tools";
import FSMessage from "@/utils/message";
import type { TabsPaneContext, FormInstance, FormRules } from "element-plus";
import useDialogsHooks from "@/views/UsualManage/UploadImage/useDialogsHooks";
import useClipboard from "vue-clipboard3";
// @ts-ignore
import Uploader from "@/components/Uploader";
// @ts-ignore
import Pagination from "@/components/Pagination";
// @ts-ignore
import Dialog from "@/components/Dialog";
/** *********************** props ****************************/
interface IProps {
  openInDialog?: boolean; // 是否在弹窗中打开该页面（选择图片使用）
}

const props = withDefaults(defineProps<IProps>(), {
  openInDialog: false
});

const emit = defineEmits(["onChange"]);

/** *********************** arg ****************************/
const state = reactive({
  visiableUpload: false, // 展示图片上传弹窗
  confirmBtnLoading: false // 上传弹窗中的确认按钮加载
});
const pageNum = ref(0);
const pageSize = ref(20);
const total = ref(200);
const pages = reactive({
  pageNum: 1,
  pageSize: 100,
  total: 0 // 页面图片总量
});
const uploaderRef = ref(null); // 上传图片组件
const dialogRef = ref(null); // 弹窗组件
const updateImgRef = ref(null); // 修改图片名称组件
const images = ref([]); // 图片列表
const imgName = ref(""); // 图片名称
const tabPosition = ref("left"); //
const keywords = ref(""); // 搜索关键字（图片名称）
const activeTabName = ref("all"); // 搜索关键字（图片名称）
const categoryList = ref([]); // tab列表
const dialogOptions = reactive({
  title: "新增分组",
  width: "400px",
  openType: 1 // 1 新增 2 编辑
});
// 分组参数
const dialogData = ref({
  name: "",
  code: ""
});
const diaformRef = ref<FormInstance>();
const currentCategoryInfo = ref<any>({ name: "全部", code: "all" }); // 当前分类信息
const currentImgInfo = ref<any>(); // 当前图片的信息
const checked = ref(null);

const {} = useDialogsHooks();
const { toClipboard } = useClipboard();

/** *********************** Functions ****************************/
const bootStrap = () => {
  query();
  queryCategories();
};
/**
 * 显示上传文件弹窗
 */
const showUploadDia = (): void => {
  state.visiableUpload = true;
};

const handleUpload = async () => {
  try {
    state.confirmBtnLoading = true;
    const res = await uploaderRef.value.uploadFile({ categoryCode: currentCategoryInfo.value.code });
    state.confirmBtnLoading = false;
    state.visiableUpload = false;
    query();
  } catch (e) {
    console.log(e);
    state.confirmBtnLoading = false;
  }
};

/**
 * @breif: 请求列表数据
 * @return {*}
 */
const query = async () => {
  try {
    const { data } = (await getImageList({ ...pages, filename: keywords.value, categoryCode: currentCategoryInfo.value.code })) || {};
    // @ts-ignore
    images.value = data.rows;
    console.log(images.value);

    // @ts-ignore
    pages.total = data.total;
  } catch (e) {
    console.log(e);
  }
};

/**
 * @breif:
 * @return {*}
 */
const queryCategories = async () => {
  const res = await getCategories({});
  categoryList.value = res.data;
};

const copyLink = (link) => {
  copyText(link, "container", () => {});
  FSMessage.success("复制成功");
};

const handleDownload = (avaliableUrl) => {
  FSSaveAs(avaliableUrl);
};

/**
 * @breif: 点击tab切换图片分类
 * @param {*} value
 * @return {*}
 */
const handleTabClick = (tab: TabsPaneContext) => {
  const item = categoryList.value.find((item) => item.code === tab.paneName);
  if (item) {
    currentCategoryInfo.value = item;
  } else {
    currentCategoryInfo.value = "all";
  }
  query();
};

/**
 * @breif: 新增分类
 * @return {*}
 */
const addCategory = () => {
  dialogOptions.openType = 1;
  dialogRef.value.visiableDialog();
  nextTick(() => {
    resetForm(diaformRef.value);
  });
};

/**
 * @breif: 新增图片分类
 * @return {*}
 */
// TODO 参数校验
const confirmOnDialog = async () => {
  try {
    dialogOptions.openType === 1 ? await createCategory(dialogData.value) : updateCategory(dialogData.value);
    queryCategories();
    dialogRef.value.invisiableDialog();
    FSMessage.success("新增成功");
  } catch (error) {
    console.log(error);
  }
};

/**
 * @breif: 重命名
 * @return {*}
 */
const reName = () => {
  dialogData.value = JSON.parse(JSON.stringify(currentCategoryInfo.value));
  dialogOptions.openType = 2;
  dialogRef.value.visiableDialog();
};

const delOneCategory = () => {
  FSMessage.confirm("是否确认删除", "警告")
    .then(() => {
      delCategory(currentCategoryInfo.value._id)
        .then((res) => {
          FSMessage.success("删除成功");
          queryCategories();
        })
        .catch(() => {
          FSMessage.success("删除失败");
        });
    })
    .catch((e) => {
      console.log(e);
    });
};
const editHanle = (item) => {
  currentImgInfo.value = item;
  updateImgRef.value.visiableDialog();
};

const pictureLink = async (item) => {
  await toClipboard(item.url);
  FSMessage.success("复制成功");
};

const changeClasstify = (command, item) => {};

// 修改图片名称
const confirmUpdateImg = async () => {
  try {
    currentImgInfo.value.filename = imgName.value;
    await updateImage(currentImgInfo.value);
    FSMessage.success("修改成功");
    updateImgRef.value.invisiableDialog();
    query();
  } catch (error) {
    console.log(error);
  }
};

const deleteImg = (id) => {
  FSMessage.confirm("是否确认删除", "警告").then(async () => {
    try {
      await delFileHard(id);
      FSMessage.success("删除成功");
      query();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleSelect = (value) => {
  emit("onChange", value);
};
bootStrap();
</script>

<style scoped lang="less">
.el-pagination {
  justify-content: flex-end;
}

.images_container {
  width: 100%;
  margin-top: 20px;

  .images {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    column-gap: 20px;
    row-gap: 40px;

    .images_item {
      width: 300px;
      padding: 6px 6px 3px 6px;
      border-radius: 5px;
      background-color: #ffffff;
    }

    .images_operator {
      display: flex;
      justify-content: space-between;
      margin-top: 6px;
      padding: 0 10px;
    }

    .el-image {
      width: 100%;
      height: 240px;
      border-radius: 5px;
    }
  }
}

.images_tags_wrapper {
  display: flex;
  padding-top: 20px;
}

.tags {
  width: 150px;
}

.img_lists {
  width: calc(100% - 170px);

  .group_name {
    display: flex;
    align-items: center;
  }

  .img_list_box {
    border: 1px solid #e8eaec;
    border-radius: 4px;
    min-height: 200px;
    margin-top: 10px;
  }
}

.image-table {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  overflow: auto;
  padding: 10px;
  background: #fefefe;
  border: 1px solid #e8eaec;

  &::after {
    content: " ";
    flex: auto;
  }

  .image-table-col {
    text-align: center;
    width: 160px;
    border-radius: 5px;

    .image-table-col-border {
      margin: 5px;
      padding: 5px 10px;
      border: 1px solid #ccc;
      border-radius: 5px;

      .image-table-image {
        height: 100px;
        overflow: hidden;
      }

      .image-table-footer {
        margin-top: 5px;
        padding-top: 5px;
        border-top: 1px dashed #eee;

        .imgae-name {
          margin: 5px 0;
          width: 100%;
          font-size: 14px;
          height: 40px;
          line-height: 20px;

          span {
            display: -webkit-box;
            /** 对象作为伸缩盒子模型显示 **/
            -webkit-box-orient: vertical;
            /** 设置或检索伸缩盒对象的子元素的排列方式 **/
            -webkit-line-clamp: 2;
            /** 显示的行数 **/
            overflow: hidden;
            /** 隐藏超出的内容**/
            text-overflow: ellipsis;
            word-wrap: break-word;
            vertical-align: middle;
          }
        }

        .image-table-footer-btn {
          :deep(.el-button) {
            padding: 2px 4px;
          }

          :deep(.el-dropdown) {
            padding: 2px 4px;
            margin-top: 4px;
            color: #1890ff;
            font-size: 12px;
            cursor: pointer;

            :deep(.el-dropdown-menu) {
              width: 150px;
            }
          }

          .deltet-btn {
            color: red;
          }
        }
      }
    }
  }
}
</style>
